package com.wdl.modules.myhouse.controller;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.wdl.modules.myhouse.common.Code;
import com.wdl.modules.myhouse.common.Result;
import com.wdl.modules.myhouse.dao.UserGameDao;
import com.wdl.modules.myhouse.entity.UserGameEntity;
import com.wdl.modules.myhouse.security.entity.UserInfo;
import com.wdl.modules.myhouse.service.GamesService;
import com.wdl.modules.myhouse.utils.util.JsonUtil;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.annotation.CurrentSecurityContext;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.Set;

/**
 * @author 昏昏的君
 */
@RequestMapping("/games")
@RestController
@Api("游戏")
public class GamesController {

    @Autowired
    private GamesService gamesService;
    @Autowired
    private UserGameDao userGameDao;


    @GetMapping("/getMyGames")
    @ApiOperation(value = "根据用户id,id,从springSecurity中拿取查找游戏", tags = "根据用户id查找游戏")
    public Result<List<JSONObject> > getMyGames(){
        Integer userId = null;
        try {
            UserInfo user = (UserInfo)SecurityContextHolder.getContext().getAuthentication().getPrincipal();
            userId = user.getId();
            if (userId==null){
                 throw new NullPointerException();
            }
        } catch (NullPointerException e) {
            return new Result<List<JSONObject> >().error(Code.UNAUTHORIZED.getCode(),"查询不到当前用户信息");
        }
        Map<Integer, Object> gamesMap = userGameDao.getGamesByUserId(userId);
        Set<Integer> keys = gamesMap.keySet();
        ArrayList<JSONObject> list = new ArrayList<>();
        for(Integer key: keys){
            Object o = gamesMap.get(key);
            list.add(JSONObject.parseObject(JsonUtil.obj2String(o)));
        }
        return new Result<List<JSONObject> >().ok().setData(list);
    }


}
